package org.example;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;


@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
@Fork(1)
@Warmup(iterations = 3)
@Measurement(iterations = 10)
public class JMHMain {

    private static YsfNode HEAD = null;

    private int res;

    @Benchmark
    public void testCalcLastOneEle() {
        initYsfNode(1000000);
        res = calcLastOneEle(3, 2);
    }

    @TearDown(Level.Iteration)
    public void showRes() {
        System.out.printf("lastOneNum：%d\t耗时：", res);
    }

    public void initYsfNode(int n) {
        if (HEAD != null) {
            return;
        }
        HEAD = new YsfNode(1, null);
        YsfNode cursorNode = HEAD;
        for (int i = 2; i <= n; i++) {
            YsfNode temp = new YsfNode(i, null);
            cursorNode.number = i;
            cursorNode.next = temp;
            cursorNode = temp;
        }
        cursorNode.next = HEAD;
    }

    public int calcLastOneEle(int startNum, int step) {
        YsfNode preNode = null;
        YsfNode cursorNode = HEAD;
        while (cursorNode != cursorNode.next) {
            if (cursorNode.number == startNum) {
                break;
            }
            cursorNode = cursorNode.next;
        }
        while (cursorNode != cursorNode.next) {
            for (int i = 1; i < step; i++) {
                preNode = cursorNode;
                cursorNode = cursorNode.next;
            }
            preNode.next = cursorNode.next;
            cursorNode = preNode.next;
        }
        return cursorNode.number;
    }


    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(JMHMain.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}